<?php
/**
 * Created by PhpStorm.
 * User: wx
 * Date: 2019/5/17
 * Time: 12:52
 */

namespace app\admin\dbhelp;
use app\admin\controller\Base;
use think\Request;

class CHelper extends Base implements IcHelper
{
    private $name;//控制器,表名称
    protected $db_helper;//控制器名称
    public function __construct($name)
    {
        parent::__construct();
        $this->name = $name;
        $db_helper = new DbHelper();
        $db_helper->name($this->name);
        $this->db_helper = $db_helper;
    }
    public function index()
    {
        $list = $this->db_helper->getAll();
        $count = $this->db_helper->getCount();
        $this->assign('_count',$count);
        $this->assign('_list',$list);
        return view($this->name.'/index');
    }
    public function add()
    {
        if($this->request->isPost())
        {
            $data = input('post.');
            $data['create_time'] = time();
            $data['update_time'] = time();
            unset($data['file']);
            $result = $this->validate($data, $this->name);
            if(true !== $result){
                return json(['code' => -5, 'url' => '', 'msg' => $result]);
            }
            $result = $this->db_helper->add($data);//新增
            if($result)
            {
                return json(['code'=>1,'msg'=>'新增成功']);
            }else{
                return json(['code'=>0,'msg'=>'新增失败']);
            }
        }else{
            return view($this->name.'/add');
        }
    }
    public function edit()
    {
        $id = input('id',0);
        if($this->request->isPost()) {
            $data = input('post.');
            $data['update_time'] = time();
            unset($data['file']);
            unset($data['id']);
            $result = $this->validate($data, $this->name);
            if(true !== $result){
                return json(['code' => -5, 'url' => '', 'msg' => $result]);
            }
            $result = $this->db_helper->edit($id, $data);
            if ($result) {
                return json(['code' => 1, 'msg' => '修改成功']);
            } else {
                return json(['code' => 0, 'msg' => '修改失败']);
            }
        }
        $obj = $this->db_helper->getOne($id);
        $this->assign('obj',$obj);
        return view($this->name.'/edit');
    }
    public function del()
    {
        $id = input('id',0);
        if($id)
        {
            $result = $this->db_helper->del($id);
            if($result)
            {
                return json(['code'=>1,'msg'=>'删除成功']);
            }else{
                return json(['code'=>0,'msg'=>'删除失败']);
            }
        }else{
            return json(['code'=>0,'msg'=>'参数错误']);
        }
    }
}